using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.SqlClient;
using System.Data.Linq.SqlClient;
using Kunlun.Models;
using Kunlun.ViewModels;
namespace Kunlun.BusinessLogic {
	public partial class KunlunProduct {

		/// <summary>
		/// 
		/// </summary>
		/// <param name="cid">类别ID</param>
		/// <param name="num">数量</param>
		public static List<Product> GetCheapProduct(int cid, int num) {
			using (KunLunEntities entities = new KunLunEntities()) {
				string categoryID = cid.ToString();
				var productlist = entities.Product.Where(i => i.Classid.Contains(categoryID) && i.Isrelease == true && i.IsCheap == true).Take(num);

				return productlist.ToList();
			}
		}

		public static List<Product> GetInputProduct(int cid, int num) {
			using (KunLunEntities entities = new KunLunEntities()) {
            try
                {
                string categoryID = cid.ToString();

                var productlist = entities.Product.Where(i => i.Classid.IndexOf("," + categoryID + ",") >= 0 && i.Isrelease == true && i.IsPut == true).Take(num);

                return productlist.ToList();
                }
            catch (Exception ex)
            {
                
                WebLog.ErrorLog(ex, "cid:" + cid.ToString() + "  num:" + num.ToString());
                return new List<Product>();
                }
			}
		}

		/// <summary>
		/// 获取相关作品
		/// </summary>
		/// <param name="cid">类别ID</param>
		/// <param name="num">数量</param>
		/// <returns>相关产品列表</returns>
		public static List<Product> GetRelationProduct(string cid, int num) {
			using (KunLunEntities entities = new KunLunEntities()) {
				var model = entities.Product.Take(6).Where(m => m.Classid.Contains(cid) && m.Isrelease == true);

				return model.ToList();
			}
		}

		/// <summary>
		/// 根据产品ID获取实体
		/// </summary>
		/// <param name="productID">产品ID</param>
        public static Product GetProductModel(string productID)
        {
            KunLunEntities entities = new KunLunEntities();
            var productmodel = entities.Product.FirstOrDefault(i => i.pid == productID && i.Isrelease == true);

            return productmodel;
        }

		/// <summary>
		/// 设置类别导航
		/// </summary>
		/// <param name="curCategoryID">产品所属类别</param>
		/// <returns></returns>
		public static List<Category> GetMenuList(int curCategoryID) {
			using (KunLunEntities entities = new KunLunEntities()) {
				var model = entities.Category.FirstOrDefault(m => m.ID == curCategoryID);
				int curParent = model.ParentID;   // 当前类的上级类

				List<Category> menulist = new List<Category>();
				while (curParent > 0) {
					var parentModel = entities.Category.FirstOrDefault(m => m.ID == curParent);
					curParent = parentModel.ParentID;
					menulist.Add(parentModel);
					if (parentModel.Sort == 1)
						break;
				}
				menulist.Add(model);

				return menulist;
			}
		}

		/// <summary>
		/// 通过类别ID获取产品集合
		/// </summary>
		/// <param name="CategoryID">产品类别ID</param>
        public static List<Product> GetProductByCategoryID(string CategoryID)
        {
            KunLunEntities entities = new KunLunEntities();
            var productList = entities.Product.Where(i => i.Classid.Contains(CategoryID) && i.Isrelease);

            if (productList == null) return null;

            return productList.ToList();
        }

		public static List<Product> GetProductPageList(int start, int size, Dictionary<string, object> where, out int count) {
			using (KunLunEntities entities = new KunLunEntities()) {
				IQueryable<Product> query = entities.Product;
				if (where != null) {
					if (where.ContainsKey("ClassID")) {
						string cid = where["ClassID"].ToString();
						query = query.Where(o => o.Classid.IndexOf("," + cid + ",") >= 0);
					}

					if (where.ContainsKey("pid")) {
						string pid = where["pid"].ToString();
						query = query.Where(o => o.pid == pid);
					}
					if (where.ContainsKey("Name")) {
						string name = where["Name"].ToString();
						query = query.Where(o => o.Name.Contains(name));
					}
				}
				count = query.Count();
				query = query.OrderByDescending(o => o.pid);
				if (start != 0) {
					query = query.Skip(start * size);
				}
				if (size != 0) {
					query = query.Take(size);
				}

				return query.ToList();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="start"></param>
		/// <param name="size"></param>
		/// <param name="where"></param>
		/// <param name="orderby">0:默认 pid 1:时间倒顺 2:价格从地到高 3:价格从高到低</param>
		/// <param name="count"></param>
		/// <returns></returns>
		public static List<Product> GetProductPageList(int start, int size, Dictionary<string, object> where, ProductSort sort, out int count) {
			using (KunLunEntities entities = new KunLunEntities()) {
				IQueryable<Product> query = entities.Product;
				if (where != null) {
					if (where.ContainsKey("Classid")) {
						string cid = where["Classid"].ToString();
						query = query.Where(o => o.Classid.IndexOf("," + cid + ",") >= 0);
					}
					if (where.ContainsKey("f")) {
						string fid = where["f"].ToString();
						query = query.Where(o => o.Classid.IndexOf("," + fid + ",") >= 0);
					}
					if (where.ContainsKey("pid")) {
						string pid = where["pid"].ToString();
						query = query.Where(o => o.pid == pid);
					}

					if (where.ContainsKey("Name")) {
						string name = where["Name"].ToString();
						query = query.Where(o => o.Name.IndexOf(name) > -1);
					}
					if (where.ContainsKey("BeginKacaprice")) {
						decimal p1 = Convert.ToDecimal(where["BeginKacaprice"]);
						query = query.Where(o => o.Kacaprice > p1);
					}
					if (where.ContainsKey("EndKacaprice")) {
						decimal p2 = Convert.ToDecimal(where["EndKacaprice"]);
						query = query.Where(o => o.Kacaprice < p2);
					}
				}

				count = query.Count();
				switch (sort) {
					case ProductSort.销量高低:
						query = query.OrderByDescending(o => o.Clicks);
						break;
					case ProductSort.价格由低到高:
						query = query.OrderBy(o => o.Kacaprice);
						break;
					case ProductSort.价格由高到低:
						query = query.OrderByDescending(o => o.Kacaprice);
						break;
					default:
						query = query.OrderByDescending(o => o.BeginDate);
						break;
				}
				if (start != 0) {
					query = query.Skip(start * size);
				}
				if (size != 0) {
					query = query.Take(size);
				}

				return query.ToList();
			}
		}

		/// <summary>
		/// 获得产品id获得产品详细信息
		/// </summary>
		/// <param name="id">产品id</param>
		/// <returns></returns>
		public static ProductsViewModels GetProductByID(string id) {
			KunLunEntities entities = new KunLunEntities();

			try {
				var product = entities.Product.FirstOrDefault(p => p.pid == id);


				ProductsViewModels model = new ProductsViewModels();
				model.Products = product;
				model.Categorys = new List<Category>();
				string[] cid = product.Classid.Split(new char[] { ',' }, StringSplitOptions.None);
				foreach (string s in cid) {
					int c;
					if (int.TryParse(s, out c)) {
						model.Categorys.Add(entities.Category.FirstOrDefault(o => o.ID == c));
					}
				}


				//增加点击///
				product.Clicks = product.Clicks + 1;
				entities.SaveChanges();
				////////
				if (model != null)

					return model;
				else
					return new ProductsViewModels();
			} catch (Exception ex) {
				WebLog.ErrorLog(ex,id);
				return new ProductsViewModels();
			}

		}

		/// 通过产品id获得属性相同的前10个产品
		/// </summary>
		/// <param name="id">产品id</param>
		/// <returns></returns>
		public static List<Product> GetInterestProductByID(string id) {
			KunLunEntities entities = new KunLunEntities();

			try {
				List<int> typeid = (from p in entities.Product_propertys
									where p.Pid == id
									select p.TypeID).ToList();
				List<string> productid = (from p in entities.Product_propertys
										  where typeid.Contains(p.TypeID) && p.Pid != id
										  select p.Pid).ToList();

				var product = (from p in entities.Product
							   where productid.Contains(p.pid) && p.P_status == 2
							   select p).Take(10).ToList();

				return product;

			} catch (Exception ex) {
                 WebLog.ErrorLog(ex, id);
				return null;
			}


		}


	}

	#region 产品规格信息  product_attributes
    public partial class KunlunProductAttribute
    {
        public static Product_attributes GetProductAttributes(int aid)
        {
            KunLunEntities entities = new KunLunEntities();
            var result = entities.Product_attributes.FirstOrDefault(m => m.ID == aid);
            return result;

        }
    }
	#endregion


	public enum ProductSort {
		上架新品 = 0,
		销量高低 = 1,
		价格由低到高 = 2,
		价格由高到低 = 3
	}
}
